/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Peer.sender;

/**
 *
 * @author user
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import FileStructure.Response;
import Peer.KoTorrentInt;
import java.net.*;
import java.io.*;
import java.util.ArrayList;
/**
 *
 * @author bangyo17
 */
public class NewHave extends Thread{
    private Socket socket;
  private BufferedReader in;
  private PrintWriter out;
  private static int counter = 0;
  private int id = counter++;
  private static int threadcount = 0;

  //get response

  private static Response resp = new Response();



  public static int threadCount() {
    return threadcount;
  }

  public static Response getResponse(){
      return resp;
  }

  public NewHave(InetAddress addr, int port, KoTorrentInt len, byte id, KoTorrentInt piece_index) {
    threadcount++;
    try {
      socket =
        new Socket(addr, port);
    } catch(IOException e) {
      // If the creation of the socket fails,

        // nothing needs to be cleaned up.
    }
    try {
      in =
        new BufferedReader(
          new InputStreamReader(
            socket.getInputStream()));
      // Enable auto-flush:
      out =
        new PrintWriter(
          new BufferedWriter(
            new OutputStreamWriter(
              socket.getOutputStream())), true);
       out.println(len.getByte(0)+len.getByte(1)+len.getByte(2)+len.getByte(3)
                    + id +
                    + piece_index.getByte(0) + piece_index.getByte(1) + piece_index.getByte(2) + piece_index.getByte(3));

      start();
    } catch(IOException e) {
      // The socket should be closed on any
      // failures other than the socket
      // constructor:
      try {
        socket.close();
      } catch(IOException e2) {}
    }
    // Otherwise the socket will be closed by
    // the run() method of the thread.
  }
  public void run() {
    try {
        //receive response
        String str = in.readLine();
        //cek response, error apa nggak
        System.out.println(str);

    } catch(IOException e) {
    } finally {
      // Always close it:
      try {
        socket.close();
      } catch(IOException e) {}
      //threadcount--; // Ending this thread
    }
  }

}
